﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebPortal.Models.EntityModels;
using WebPortal.Models.ViewModel;

namespace WebPortal.Controllers
{
    public class GoodsController : BaseController
    {
        //
        // GET: /Goods/

        public ActionResult Index()
        {
            GoodsList goods = new GoodsList();
            goods.goods = (from good in dbGoods.Goods select good).ToList();
            goods.categories = (from cat in dbCategories.Categories select cat).ToList();
            return View(goods);
        }

        public ActionResult Add(Goods g)
        {
            string basePath = "D:\\Tools\\ASP\\WebPortal\\Content\\Img\\";
            HttpPostedFileBase file = Request.Files["picture"];
            string filePath = null;
            if (file.ContentLength > 0)
            {
                filePath = new Random().Next(99999, 999999).ToString() + file.FileName;
                file.SaveAs(basePath + filePath);
            }
            Goods good = new Goods();
            good.Description = g.Description;
            good.Name = g.Name;
            good.CategoryID = g.CategoryID;
            good.Picture = filePath;
            dbGoods.AddToGoods(good);
            try
            {
                dbGoods.SaveChanges();
            }
            catch (System.Data.UpdateException e)
            {
                //Can not insert to database
            }
            return this.RedirectToAction("Index");
        }

        public ActionResult Delete(Goods g)
        {
            var goods = (from good in dbGoods.Goods where good.GoodID == g.GoodID select good).ToList();
            dbGoods.DeleteObject(goods[0]);
            try
            {
                dbGoods.SaveChanges();
            }
            catch (System.Data.UpdateException e)
            {
                //Can not insert to database
            }
            return this.RedirectToAction("Index");
        }

    }
}
